package com.robertux.leaderboard.servlets;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

/**
 * Filtro del usuario en sesión
 */
@WebFilter(filterName="/UserSessionFilter", urlPatterns={"/index.html", "/admin/*", "/consultas/*"})
public class UserSessionFilter implements Filter {
	public static final String LOGIN_PAGE = "/Leaderboard/login.html";
	private Logger logger;

	public void destroy() {
		
	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		this.logger.debug("Dentro del WebFilter");
		HttpServletRequest req = (HttpServletRequest)request;
		HttpServletResponse resp = (HttpServletResponse)response;
		HttpSession session = req.getSession(false);
		
		String origin = req.getHeader("referer");
		this.logger.debug("Página de origen: " + origin);
		
		if(null == session || null == session.getAttribute(BaseServlet.USR_SESSION_NAME) 
				|| session.getAttribute(BaseServlet.USR_SESSION_NAME).toString().trim().length() == 0) {
			
			this.logger.debug("Usuario no logueado!");
			resp.sendRedirect(LOGIN_PAGE);
			return;
		}
		this.logger.debug("Objeto sesion existe y el usuario logueado es " + session.getAttribute(BaseServlet.USR_SESSION_NAME));
		
		chain.doFilter(request, response);
	}

	public void init(FilterConfig fConfig) throws ServletException {
		this.logger = Logger.getLogger(this.getClass());
	}

}